const Router = require('koa-router');
const multer = require('koa-multer');
const { getDB } = require('../modules/db');

const router = new Router();



// 配置上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/muti'); // 确保这个文件夹已经存在
  },
  // 修改文件名称
  filename: function(req, file, cb) {
    //  获取后缀名
    const ext = file.originalname.split('.');
    // 指定上传文件的文件名
    cb(null, Date.now() + '.' + ext[ext.length - 1]);
  },
});

const upload = multer({ storage: storage });


// 处理上传的文件
// 多文件上传
router.post('/muti', upload.array('file', 10), async (ctx, next) => {

  // 获取上传文件的信息
  const { files } = ctx.req;

  // 额外参数
  const { name } = ctx.req.body;

  // 数据库交互
  const { find, close } = getDB();

  const con = find();

  // 遍历图片地址
  const cacheURL = files.map(item => `http://localhost:3000/muti/${item.filename}`);

  try {

        const [rows] = await con.execute(
            'INSERT INTO `files` (`name`, `url`, `count`) VALUE (?, ?, ?)',
            [name, JSON.stringify(cacheURL), cacheURL.length]
        );

        if (rows.affectedRows === 0) {
            ctx.body = {
                success: false,
                code: 400,
                msg: "上传失败"
            }
            return;
        }

        ctx.body = {
            success: true,
            code: 200,
            msg: `成功上传${cacheURL.length}张图片`
        }
        return;
    } catch (error) {
        ctx.body = {
            success: false,
            code: 500,
            msg: "服务器错误",
            error
        }
    }
    finally {
        // 释放连接
        close();
    }
});

module.exports = router;